package org.sxm.cloud.response;

import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.sxm.cloud.result.ApiResult;

import java.util.Objects;

/**
 * @Description
 * @Author xmSheng
 * @Date 2024/1/22
 */
@RestControllerAdvice
public class ResponseHandler implements org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice {



    /**
     * 判断是否对响应进行处理
     *
     * @param returnType
     * @param converterType
     * @return
     */
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        /**
         * OpenFegin内部调用，在Header中加了标志位，解析是否为OpenFegin调用
         */
        /*
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        String innerService = request.getHeader(ReqeustConstants.INNER_SERVICE);
        if(StringUtils.isNotBlank(innerService)){
             return false;
        }*/
        return true;
    }

    /**
     * 响应客户端之前处理，返回给前端统一封装ApiReuslt，Fegin微服务内部调用，直接返回对象
     *
     * @param o
     * @param returnType
     * @param selectedContentType
     * @param selectedConverterType
     * @param request
     * @param response
     * @return
     */
    @Override
    public Object beforeBodyWrite(Object o, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        //返回参数为空
        if (Objects.isNull(o)) {
            return ApiResult.success();
        }
        //返回参数本生就是ApiResult
        if (o instanceof ApiResult) {
            return o;
        }
        //包装
        return ApiResult.success(o);
    }

}
